const Koa = require('koa')
const path = require('path')
const fs = require('fs')
const config = process.env.NODE_ENV === 'development' ? require('../config/index.dev') : require('../config/index')
const send = require('koa-send')
const sharp = require('sharp')
const util = require('./utils')
const app = new Koa()
const imageRootPath = path.isAbsolute(config.ROOTPATH) ? config.ROOTPATH : path.join(process.cwd(), config.ROOTPATH)
const cacheRootPath = path.isAbsolute(config.CACHEPATH) ? config.CACHEPATH : path.join(process.cwd(), config.CACHEPATH)
function generateCachePath (ctx) {
  let [width, height, cachePath] = [null, null, null, null]
  cachePath = path.join(cacheRootPath, ctx.path)
  if (Object.prototype.hasOwnProperty.call(ctx.query, 'width') || Object.prototype.hasOwnProperty.call(ctx.query, 'height')) {
    width = parseInt(ctx.query.width) || null
    height = parseInt(ctx.query.height) || null
    return cachePath.replace(/\./, '_' + width + '_' + height + '.')
  } else if (Object.getOwnPropertyNames(ctx.query).length === 0) {
    return cachePath.replace(/\./, '_wite_watermark.')
  } else {
    return path.join(imageRootPath, ctx.path)
  }
}
app.use(async ctx => {
  // 检测原始文件是否存在
  if (!fs.existsSync(path.join(imageRootPath, ctx.path))) {
    ctx.status = 404
    return
  }
  const cachePath = await generateCachePath(ctx)
  // console.log(cachePath)
  // 判断缓存文件是否存在，存在则直接返回
  if (fs.existsSync(cachePath)) {
    return send(ctx, cachePath, { root: '/' })
  } else {
    // 检测并创建缓存目录
    await util.createIfNotExist(path.dirname(cachePath))
    // 是否加水印图片
    if (Object.prototype.hasOwnProperty.call(ctx.query, 'width') || Object.prototype.hasOwnProperty.call(ctx.query, 'height')) {
      const width = parseInt(ctx.query.width) || null
      const height = parseInt(ctx.query.height) || null
      await sharp(path.join(imageRootPath, ctx.path)).resize(width, height).toFile(cachePath).then(info => {
        // 返回结果
        return send(ctx, cachePath, { root: '/' })
      })
    } else if (Object.getOwnPropertyNames(ctx.query).length === 0) {
      // 生成水印图片
      await sharp(path.join(imageRootPath, ctx.path)).overlayWith(config.WATERMARK, { gravity: sharp.gravity.southeast }).toFile(cachePath).then(info => {
        // 返回结果
        return send(ctx, cachePath, { root: '/' })
      })
    } else {
      return send(ctx, path.join(imageRootPath, ctx.path), { root: '/' })
    }
  }
})
module.exports = app
